package com.ttxz.common.http

import android.text.TextUtils
import com.ttxz.common.constants.CommonConstant
import com.ttxz.common.utils.log.LogUtil
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.joor.Reflect
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 简要说明
 *
 * @author ttxz
 * @date 2022/6/15 8:51
 */
object RetrofitManager {
    private lateinit var mRetrofit: Retrofit

    fun <T> create(clazz: Class<T>?): T {
        return mRetrofit.create(clazz)
    }

    init {
        //使用默认的baseUrl初使化retrofit实例
        initRetrofit()
    }

    /**
     * 使用默认的baseUrl初使化retrofit实例
     */
    fun initRetrofit(){
        val okHttpClient: OkHttpClient = OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .callTimeout(30, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build()
        val baseUrlTemp = if (TextUtils.isEmpty(CommonConstant.BASE_URL)) {
            "http://192.168.1.1:9001"
        }else{
            CommonConstant.BASE_URL
        }
        mRetrofit = Retrofit.Builder()
            .baseUrl(baseUrlTemp)
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()
    }

    fun resetBaseurl(baseUrl: String) {
        CommonConstant.BASE_URL = baseUrl
        val httpUrl = baseUrl.toHttpUrlOrNull()
        if (httpUrl == null) {
            LogUtil.e("HttpUrl解析失败")
            throw IllegalArgumentException("Illegal URL: $baseUrl")
        }

        //Baseurl发生变化，重新初始化Retrofit
        initRetrofit()

    }

}